package com.fh.controller.system.supervisor;

import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.fh.controller.base.BaseController;
import com.fh.entity.Page;
import com.fh.util.AppUtil;
import com.fh.util.DateUtil;
import com.fh.util.FileDownload;
import com.fh.util.FileUpload;
import com.fh.util.ObjectExcelRead;
import com.fh.util.ObjectExcelView;
import com.fh.util.Const;
import com.fh.util.PageData;
import com.fh.util.PathUtil;
import com.fh.util.Tools;
import com.fh.util.Jurisdiction;
import com.fh.service.system.dictionaries.DictionariesService;
import com.fh.service.system.menu.MenuService;
import com.fh.service.system.role.RoleService;
import com.fh.service.system.supervisor.SupervisorService;

/** 
 * 类名称：SupervisorController
 * 创建人：FH 
 * 创建时间：2015-08-02
 */
@Controller
@RequestMapping(value="/supervisor")
public class SupervisorController extends BaseController {
	
	String menuUrl = "supervisor/list.do"; //菜单地址(权限用)
	@Resource(name="supervisorService")
	private SupervisorService supervisorService;
	
	@Resource(name="roleService")
	private RoleService roleService;
	
	
	@Resource(name="dictionariesService")
	private DictionariesService dictionariesService;
	
	
	@Resource(name="menuService")
	private MenuService menuService;
	
	/**
	 * 获取登录用户的IP
	 * @throws Exception 
	 */
	public void getRemortIP(String USERNAME) throws Exception {  
		PageData pd = new PageData();
		HttpServletRequest request = this.getRequest();
		String ip = "";
		if (request.getHeader("x-forwarded-for") == null) {  
			ip = request.getRemoteAddr();  
	    }else{
	    	ip = request.getHeader("x-forwarded-for");  
	    }
		pd.put("USERNAME", USERNAME);
		pd.put("LAST_IP", ip);
		supervisorService.saveIP(pd);
	}  
	
	/**
	 * 新增
	 */
	@RequestMapping(value="/save")
	public ModelAndView save() throws Exception{
		logBefore(logger, "新增Supervisor");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "add")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("SUPERVISOR_ID", this.get32UUID());//主键
		
		
		pd.put("LAST_TIME", DateUtil.getTime().toString());				//最后登录时间
		supervisorService.updateLastLogin(pd);
		pd.put("LAST_IP", "");						//IP
		
		
		supervisorService.save(pd);
		mv.addObject("msg","success");
		mv.setViewName("save_result");
		return mv;
	}
	
	/**
	 * 删除
	 */
	@RequestMapping(value="/delete")
	public void delete(PrintWriter out){
		logBefore(logger, "删除Supervisor");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "del")){return;} //校验权限
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			supervisorService.delete(pd);
			out.write("success");
			out.close();
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
	}
	
	/**
	 * 修改
	 */
	@RequestMapping(value="/edit")
	public ModelAndView edit() throws Exception{
		logBefore(logger, "修改Supervisor");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		supervisorService.edit(pd);
		mv.addObject("msg","success");
		mv.setViewName("save_result");
		return mv;
	}
	
	/**
	 * 列表
	 */
	@RequestMapping(value="/list")
	public ModelAndView list(Page page){
		logBefore(logger, "列表Supervisor");
		//if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;} //校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			page.setPd(pd);
			List<PageData>	varList = supervisorService.list(page);	//列出Supervisor列表
			mv.setViewName("system/supervisor/supervisor_list");
			mv.addObject("varList", varList);
			mv.addObject("pd", pd);
			mv.addObject(Const.SESSION_QX,this.getHC());	//按钮权限
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/**
	 * 去新增页面
	 */
	@RequestMapping(value="/goAdd")
	public ModelAndView goAdd(){
		logBefore(logger, "去新增Supervisor页面");
		ModelAndView mv = this.getModelAndView();
		try {
			PageData pd = new PageData();
			pd.put("P_BM", "YX");
			List<PageData> roleList = dictionariesService.dictlistPagebyp_bm(pd);
			mv.addObject("roleList", roleList);
			mv.setViewName("system/supervisor/supervisor_edit");
			mv.addObject("msg", "save");
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	
	/**
	 * 去修改页面
	 */
	@RequestMapping(value="/goEdit")
	public ModelAndView goEdit(){
		logBefore(logger, "去修改Supervisor页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			PageData pdp = new PageData();
			pdp.put("P_BM", "YX");
			List<PageData> roleList = dictionariesService.dictlistPagebyp_bm(pdp);
			mv.addObject("roleList", roleList);
			pd = supervisorService.findById(pd);	//根据ID读取
			mv.setViewName("system/supervisor/supervisor_edit");
			mv.addObject("msg", "edit");
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	
	/**
	 * 批量删除
	 */
	@RequestMapping(value="/deleteAll")
	@ResponseBody
	public Object deleteAll() {
		logBefore(logger, "批量删除Supervisor");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "dell")){return null;} //校验权限
		PageData pd = new PageData();		
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			pd = this.getPageData();
			List<PageData> pdList = new ArrayList<PageData>();
			String DATA_IDS = pd.getString("DATA_IDS");
			if(null != DATA_IDS && !"".equals(DATA_IDS)){
				String ArrayDATA_IDS[] = DATA_IDS.split(",");
				supervisorService.deleteAll(ArrayDATA_IDS);
				pd.put("msg", "ok");
			}else{
				pd.put("msg", "no");
			}
			pdList.add(pd);
			map.put("list", pdList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			logAfter(logger);
		}
		return AppUtil.returnObject(pd, map);
	}
	
	/*
	 * 导出到excel
	 * @return
	 */
	@RequestMapping(value="/excel")
	public ModelAndView exportExcel(){
		logBefore(logger, "导出Supervisor到excel");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;}
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try{
			Map<String,Object> dataMap = new HashMap<String,Object>();
			List<String> titles = new ArrayList<String>();
			titles.add("用户名");	//1
			titles.add("登录密码");	//2
			titles.add("姓名");	//3
			titles.add("所属学院");	//4
			titles.add("本、专科");
			titles.add("限选人数");
			titles.add("已选人数");
			titles.add("最后登录时间");	//5
			titles.add("上次登录ip");	//6
			titles.add("电子邮件");	//7
			titles.add("电话");	//8
			titles.add("QQ");	//9
			titles.add("导师简介");	//10
			titles.add("导师学历");	//11
			titles.add("导师职称");	//12
			titles.add("是否删除");	//13
			titles.add("备注");	//14
			dataMap.put("titles", titles);
			List<PageData> varOList = supervisorService.listAll(pd);
			List<PageData> varList = new ArrayList<PageData>();
			for(int i=0;i<varOList.size();i++){
				PageData vpd = new PageData();
				vpd.put("var1", varOList.get(i).getString("USERNAME"));	//1
				vpd.put("var2", varOList.get(i).getString("PASSWORD"));	//2
				vpd.put("var3", varOList.get(i).getString("SUPERVISOR"));	//3
				vpd.put("var4", varOList.get(i).getString("DEPARTMENT_XI"));
				vpd.put("var5", varOList.get(i).getString("XIANXUAN"));
				vpd.put("var6", varOList.get(i).getString("S_MAXNUMBER"));
				vpd.put("var7", varOList.get(i).getString("S_CURRENTNUMBER"));//4
				vpd.put("var8", varOList.get(i).getString("LAST_TIME"));	//5
				vpd.put("var9", varOList.get(i).getString("LAST_IP"));	//6
				vpd.put("var10", varOList.get(i).getString("EMAIL"));	//7
				vpd.put("var11", varOList.get(i).getString("TELPHONE"));	//8
				vpd.put("var12", varOList.get(i).getString("QQ"));	//9
				vpd.put("var13", varOList.get(i).getString("INTRODUCE"));	//10
				vpd.put("var14", varOList.get(i).getString("EDUCATION"));	//11
				vpd.put("var15", varOList.get(i).getString("TECHNICAL"));	//12
				vpd.put("var16", varOList.get(i).getString("IS_DEL"));	//13
				vpd.put("var17", varOList.get(i).getString("REMARK"));	//14
				varList.add(vpd);
			}
			dataMap.put("varList", varList);
			ObjectExcelView erv = new ObjectExcelView();
			mv = new ModelAndView(erv,dataMap);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	/**
	 * 打开上传EXCEL页面
	 */
	@RequestMapping(value="/goUploadExcel")
	public ModelAndView goUploadExcel()throws Exception{
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("system/supervisor/uploadexcel");
		return mv;
	}
	
	/**
	 * 下载模版
	 */
	@RequestMapping(value="/downExcel")
	public void downExcel(HttpServletResponse response)throws Exception{
		
		FileDownload.fileDownload(response, PathUtil.getClasspath() + Const.FILEPATHFILE + "Supervisor.xls", "Supervisor.xls");
		
	}
	
	/**
	 * 从EXCEL导入到数据库
	 */
	@RequestMapping(value="/readExcel")
	public ModelAndView readExcel(
			@RequestParam(value="excel",required=false) MultipartFile file
			) throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		
		if (null != file && !file.isEmpty()) {
			String filePath = PathUtil.getClasspath() + Const.FILEPATHFILE;								//文件上传路径
			String fileName =  FileUpload.fileUp(file, filePath, "supervisorexcel");							//执行上传
			
			List<PageData> listPd = (List)ObjectExcelRead.readExcel(filePath, fileName, 1, 1, 0);	//执行读EXCEL操作,读出的数据导入List 1:从第2行开始；0:从第A列开始；0:第0个sheet
			
			/*存入数据库操作======================================*/
			pd.put("LAST_TIME", "");				//最后登录时间
			pd.put("LAST_IP", "");						//IP
			
			/**
			 * var0:序号
			 * var1:用户名	
			 * var2 :登录密码	
			 * var3:姓名
			 * var4:所属学院	
			 * var5:最后登录时间	
			 * var6:最后一次登录IP
			 * var7:电子邮件	
			 * var8:电话	
			 * var9:QQ
			 * var10:导师简介
			 * var11:导师学历
			 * var12:导师职称
			 * var13:是否删除
			 * var14:备注
			 
			  */
			for(int i=0;i<listPd.size();i++){		
				pd.put("SUPERVISOR_ID", this.get32UUID());										//ID
				pd.put("USERNAME", listPd.get(i).getString("var1"));							//姓名
				
				
				if(supervisorService.findByUsername(pd) != null){										//判断用户名是否重复
					continue;
				}
				
				pd.put("PASSWORD", listPd.get(i).getString("var2"));							//编号已存在就跳过
				pd.put("NAME", listPd.get(i).getString("var3"));
				pd.put("DEPARTMENTID", listPd.get(i).getString("var4"));
				//pd.put("LAST_TIME", listPd.get(i).getString("var5"));
				//pd.put("LAST_IP", listPd.get(i).getString("var6"));
				pd.put("EMAIL", listPd.get(i).getString("var7"));
				pd.put("TEL", listPd.get(i).getString("var8"));
				pd.put("QQ", listPd.get(i).getString("var9"));
				pd.put("INTRODUCE", listPd.get(i).getString("var10"));
				pd.put("EDUCATION", listPd.get(i).getString("var11"));
				pd.put("TECHNICAL", listPd.get(i).getString("var12"));
				pd.put("IS_DEL", listPd.get(i).getString("var13"));
				pd.put("REMARK", listPd.get(i).getString("var14"));
				supervisorService.save(pd);
			}
			/*存入数据库操作======================================*/
			
			mv.addObject("msg","success");
		}
		
		mv.setViewName("save_result");
		return mv;
	}
	
	/* ===============================权限================================== */
	public Map<String, String> getHC(){
		Subject currentUser = SecurityUtils.getSubject();  //shiro管理的session
		Session session = currentUser.getSession();
		return (Map<String, String>)session.getAttribute(Const.SESSION_QX);
	}
	/* ===============================权限================================== */
	
	@InitBinder
	public void initBinder(WebDataBinder binder){
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(format,true));
	}
	
}
